package jmind.dolphin.redis.server.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import jmind.dolphin.frame.Dispatcher;
import jmind.dolphin.frame.DolphinCommand;
import jmind.dolphin.redis.Command;
import jmind.dolphin.redis.InlineReply;
import jmind.dolphin.redis.Reply;
import jmind.dolphin.redis.StatusReply;

import static jmind.dolphin.redis.ErrorReply.NYI_REPLY;
import static jmind.dolphin.redis.StatusReply.QUIT;


/**
 * Handle decoded commands
 */
@ChannelHandler.Sharable
public class DolphinServerHandler extends SimpleChannelInboundHandler<Command> {


  @Override
  public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    ctx.flush();
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
          throws Exception {
    ctx.fireExceptionCaught(cause);
  }

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, Command msg) throws Exception {

    Reply reply= Dispatcher.getInstance().dispatch(new DolphinCommand(msg));

    if (reply == QUIT) {
      ctx.close();
    } else {

      if (reply == null) {
        reply = NYI_REPLY;
      }
      ctx.write(reply);
    }
  }
}
